<?php

// $Log: index.php,v $
// Revision 1.4  2006/05/25 12:18:32  rdmp1c
// Added modifications from Nicky Nicolson (Kew)
//

// N.Nicolson, May 2006 - Added logic to follow HTTP 302 redirects.

/**
 * @file LSID.php
 *
 * @brief LSID client
 *
 */

require_once("config.inc.php");
require_once("Net/DNS.php");

/**
 *@brief Encapsulate a LSID
 *
 */

class LSID {

	var $lsid;
	var $authority;
	var $namespace;
	var $object;
	var $revision;
	
	
	function LSID ($urn)
	{
		$this->lsid = $urn;
		if ($this->isValid())
		{
			$this->components();
		}
	}
	
	function asString ()
	{
		return $this->lsid;
	}

	/**
	 * @brief Test whether LSID is syntactically correct.
	 *
	 * Uses a regular expression taken from IBM's Perl stack.
	 *
	 * @return True if LSID is valid. 
	 *
	 */
	function isValid()
	{
		return preg_match ("/^[uU][rR][nN]:[lL][sS][iI][dD]:[A-Za-z0-9][\w\(\)\+\,\-\.\=\@\;\$\"\!\*\']*:[A-Za-z0-9][\w\(\)\+\,\-\.\=\@\;\$\"\!\*\']*:[A-Za-z0-9][\w\(\)\+\,\-\.\=\@\;\$\"\!\*\']*(:[A-Za-z0-9][\w\(\)\+\,\-\.\=\@\;\$\"\!\*\']*)?$/", $this->lsid);
	}
	
	/**
	 * @brief Extract component parts of LSID.
	 *
	 */
	function components()
	{
		$components = split(':', $this->lsid);
		$this->authority = $components[2];
		$this->namespace = $components[3];
		$this->object = $components[4];
		if (isset($components[5]))
		{
			$this->revision = $components[5];
		}
		else
		{
			$this->revision = '';
		}
	}
	
	function getAuthority()
	{
		return $this->authority;
	}

}

/**
 *@brief Encapsulate a LSID authority
 *
 */

class Authority {

	var $server;
	var $port;
	var $wsdl;
	var $service_wsdl;
	var $httpBinding;
	var $httpMetadataBinding;
	var $http_code;
	var $lsid_code;
	var $http_proxy;
	var $report;
	var $debug;
	var $lsid;
	var $lsid_error_code;
	var $header_counter;
	var $stored_wsdl;

	function Authority ($proxy = '')
	{
		$this->http_proxy = $proxy;
		
		$this->server 	= '';
		$this->port 	= '';
		
		$this->report = true;
		$this->debug = false;
		
		$this->lsid_error_code = 0;
		
		$this->header_counter = 0;
	
	}
	
	function storeServiceWSDL()
	{
		$this->stored_wsdl  = $this->service_wsdl;
	}
	function restoreServiceWSDL()
	{
		$this->service_wsdl  = $this->stored_wsdl;
	}
	
	function getLSIDError()
	{
		return $this->lsid_error_code;
	}
	/**
	 * @brief Resolve a LSID using the DNS
	 *
	 * 
	 */
	function Resolve ($lsid_to_resolve)
	{
		$result = true;
		
		$this->lsid = new LSID($lsid_to_resolve);
		
		$ndr = new Net_DNS_Resolver();
		$answer = $ndr->search("_lsid._tcp." . $this->lsid->getAuthority(), "SRV");
		
		if ($answer == false)
		{
			$result = false;
			
		}
		else
		{
			if ($this->debug)
			{
				echo "<pre>";
				print_r ($answer->answer);
				echo "</pre>";
			}
		}
		
		$this->server = $answer->answer[0]->target;
		$this->port = $answer->answer[0]->port;
		
		if ($this->report)
		{
			echo "<p>";
			echo "Authority for <strong>$lsid_to_resolve</strong> ";
			if ($result)
			{
				echo "is located at: ", $this->server, ":", $this->port;
			}
			else
			{
				echo "not found";
			}
			echo "</p>";
		}
		
		return $result;
	}
	
	function GetLocation ()
	{
		return $this->server . ":" . $this->port;
	}
	

	/**
	 * @brief Display the HTTP headers
	 *
	 * @param We use some simple Javascript to enable user to toggle on and off
	 * the header display.
	 */
	function ShowHTTPHeader ($header, $prefix = '')
	{
	
	?>
	
<div >
	<table width="100%" border="0">
	<tr><td align="right">
	
		<?php echo "<span id=\"$prefix", "showHeaders\" href=\"#\" onclick=\"showHeaders('$prefix');return false;\">"; ?>
		HTTP headers <img src="images/expand.gif" align="center"/>
		</span>
		<?php echo "<span id=\"$prefix", "collapseHeaders\" href=\"#\" onclick=\"hideHeaders('$prefix');return false;\" style=\"display:none;\">"; ?>
		HTTP headers <img src="images/collapse.gif" align="center"/>
		</span>
	</td></tr>
	</table>
</div>


	<?php
	
		echo "<div id=\"$prefix", "headerRow\" style=\"display:none;\">\n"; 
		echo "<table width=\"100%\" border=\"0\" class=\"details\">\n";
		$rows = split ("\n", $header);
		foreach ($rows as $row)
		{
			$parts = split (":", $row, 2);
			if (count($parts) == 1)
			{
				if (preg_match("/HTTP\//", $row))
				{
					echo "<tr>";
					echo "<td>", "Status", "</td>";
					echo "<td>", $row, "</td>";
					echo "</tr>";			
				
				}
			}
			else
			{
				echo "<tr>";
				echo "<td>", $parts[0], "</td>";
				echo "<td>", $parts[1], "</td>";
				echo "</tr>\n";			
			}
		}
		echo "<tr><td></td><td></td></tr>\n";
		echo "</table>\n";
		echo "</div>\n";
	
	
	}
	
	
	
	/**
	 * @brief Get a WSDL using HTTP GET
	 *
	 * @param url the URL for the WSDL
	 * @param prefix an optional prefix to distinguish this WSDL
	 *
	 */
	function GetWSDL ($url, $prefix = '')
	{
		$result = false;
		$this->lsid_error_code = 0;
		
		$wsdl = '';
		$ch = curl_init(); 
		curl_setopt ($ch, CURLOPT_URL, $url); 
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 	1); 
		curl_setopt ($ch, CURLOPT_HEADER,			1); 
		curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
		
		
		curl_setopt ($ch, CURLOPT_PROXY, $this->http_proxy);
		
		//echo "<b>Proxy: ", $this->http_proxy, "</b>";
		
		
		$wsdl=curl_exec ($ch); 
		
//		if( curl_errno ($ch) != 0 )
//		{
//			echo "CURL error: ", curl_error($ch);
//		}
//		else
		{
			 $info = curl_getinfo($ch);
			 
			 $header = substr($wsdl, 0, $info['header_size']);
			 
			 $this->http_code = $info['http_code'];

			 if ($this->HttpCodeValid($this->http_code))
			 {
			 	// Everything seems OK
			 
			 }
			 else
			 {
			 	
			 	// Extract LSID error code, if any
			 	
				$rows = split ("\n", $header);
				foreach ($rows as $row)
				{
					$parts = split (":", $row, 2);
					if (count($parts) == 2)
					{
						if (preg_match("/LSID-Error-Code/", $parts[0]))
						{
							$this->lsid_error_code = $parts[1];
						}
					}
				}

			 }
			 
			 //print_r($info);
			 
			 
			 if ($this->report)
			 {
				if (!$this->HttpCodeValid($this->http_code))
			 	{
					echo "<p><strong>HTTP error: ", $this->http_code, "</strong></p>";
				}
			 	if ($this->lsid_error_code != 0)
			 	{
					echo "<p><strong>LSID error: ", $this->lsid_error_code, "</strong></p>";
				}
			 	$this->ShowHTTPHeader($header, $prefix);
			 }
			 
			 if (($this->HttpCodeValid($this->http_code)) && ($this->lsid_error_code == 0))
			 {
				$wsdl = substr ($wsdl,$info['header_size']);
				$result = $wsdl;
			}
		}
		curl_close ($ch); 
		
		/*echo "<div><b>Debug</b>";
		echo htmlentities($wsdl);
		echo "</div>";*/
		
		return $result;
	}
	
	function CacheAuthorityWSDL ()
	{
		global $config;
		$cache_authority = $config['cache_dir']. "/" . $this->lsid->authority;
		$cache_filename = $cache_authority . "/authority.wsdl";
				
		// Ensure cache subfolder exists for this authority
		if (!file_exists($cache_authority))
		{
			$oldumask = umask(0); 
			mkdir($cache_authority, 0777);
			umask($oldumask);
		}
		
		// Store data in cache
		$cache_file = @fopen($cache_filename, "w+") or die("could't open file --\"$cache_filename\"");
		@fwrite($cache_file, $this->wsdl);
		fclose($cache_file);
	}


	function CacheMetadata ($metadata)
	{	
		global $config;
		
		$extension = 'xml';
		if (preg_match("/rdf:RDF/", $metadata))
		{
			$extension = 'rdf';
		}
		$filename = md5($this->lsid->asString()) . "." . $extension;
		$cache_authority = $config['cache_dir'] . "/" . $this->lsid->authority;
		$cache_filename = $cache_authority . "/" . $filename;
		
		
		// Ensure cache subfolder exists for this authority
		if (!file_exists($cache_authority))
		{
			$oldumask = umask(0); 
			mkdir($cache_authority, 0777);
			umask($oldumask);
		}
			
		// Store data in cache
		$cache_file = @fopen($cache_filename, "w+") or die("could't open file \"--$cache_filename\"");
		@fwrite($cache_file, $metadata);
		fclose($cache_file);
		
		return $filename;
	}

	/**
	 * @brief Get WSDL describing the authority 
	 *
	 * 
	 */
	function GetAuthorityWSDL ()
	{
		$url = $this->server . ":" .  $this->port . "/authority/";
		$this->wsdl = $this->GetWSDL ($url);
		
		if ($this->wsdl === false) 
		{ 
			return false; 
		} 
		else 
		{
			$this->CacheAuthorityWSDL();
			
			if ($this->report)
			{
				$src = "get.php?src=" . $this->lsid->getAuthority() . "/authority.wsdl";
				echo "\n<div>\n";
				echo "<table width=\"100%\">\n";
				echo "<tr><td><iframe style=\"width:100%\" frameborder=\"0\" vspace=\"0\" hspace=\"0\" marginwidth=\"0\" marginheight=\"0\" height=\"200\" src=\"$src\"></iframe></td></tr>\n";
				echo "</table>\n";
				echo "</div>\n";
			}
			return true;
		}
	}

	/**
	 * @brief Get WSDL describing the available services
	 *
	 * 
	 */
	function GetServiceWSDL ($l)
	{
		$url = $this->httpBinding . "/authority/?lsid=" . $l;
		echo $url;
		
		$this->header_counter++;
		$this->service_wsdl = $this->GetWSDL ($url, $this->header_counter);
		if ($this->service_wsdl == false) { return false; } else {return true;}
	}
	
	/**
	 * @brief Get HTTP binding for LSID authority
	 *
	 * Why oh why do we use regular expressions to parse XML? Because the WSDL files may or may not
	 * have namespaces, and the obvious XPath solution (using local-name()) doesn't work
	 * in XPath.class, which means PHP 4 can't use XPath. Hence, we do this.
	 *
	 * Idea comes from Jack Herrington's article "Reading and writing the XML DOM with PHP"
	 * http://www-128.ibm.com/developerworks/library/os-xmldomphp/
	 *
	 */
	function GetHTTPBinding ()
	{
		$this->httpBinding = '';
		preg_match_all( "/\<[A-Za-z0-9]*[:]?service(.*?)\<\/[A-Za-z0-9]*[:]?service\>/s", $this->wsdl, $services);
				
		foreach( $services[1] as $service )
		{
			preg_match_all( "/\<[A-Za-z]*[:]?port (.*?)\<\/[A-Za-z]*[:]?port\>/s", $service, $ports );

			foreach ($ports[1] as $port)
			{
				preg_match_all ("/LSIDAuthorityHTTPBinding/", $port, $binding);

				if (isset($binding[0][0]))
				{
					preg_match_all( "/\<[A-Za-z]*[:]?address\s+location=\"(.*?)\"\s*\/\>/", $port, $location );
					
					$this->httpBinding = $location[1][0];

					// Strip off any trailing '/'
					$this->httpBinding = rtrim($this->httpBinding, "/");
					
				}
			}
		}
		
		if ($this->report)
		{
			echo "<p>Authority HTTP binding: <b>", $this->httpBinding, "</b></p>\n";
		}
		$result = ($this->httpBinding != '');
		return $result;
	}
	
	/*
	 * @brief Check that HTTP binding for authority is a server address (i.e., nothing after http://my.web.com[:80]/)
	 *
	 */
	function bindingIsServerAddress ()
	{
		return 	preg_match ("/^https?:\/\/([a-z0-9\-]*[a-z0-9]?\.)+(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|[a-z][a-z])(:[0-9]{2,4})?(\/?)$/",  $this->httpBinding);
	}

	function GetMetadataHTTPLocation()
	{
/*		echo "<h1>Hello</h1>";
		
		echo "WSDL=";
		echo $this->service_wsdl;
		echo "done";
*/	
		preg_match_all( "/\<[A-Za-z0-9]*[:]?service(.*?)\<\/[A-Za-z0-9]*[:]?service\>/s", $this->service_wsdl, $services);
		
		foreach( $services[1] as $service )
		{
			preg_match_all( "/\<[A-Za-z]*[:]?port (.*?)\<\/[A-Za-z]*[:]?port\>/s", $service, $ports );
			foreach ($ports[1] as $port)
			{
				preg_match_all ("/LSIDMetadataHTTPBinding/", $port, $binding);
				if (isset($binding[0][0]))
				{
					preg_match_all( "/\<[A-Za-z]*[:]?address\s+location=\"(.*?)\"\s*\/\>/", $port, $location );
					
					$this->httpMetadataBinding = $location[1][0];
					$this->httpMetadataBinding = rtrim($this->httpMetadataBinding, "/");
				}
			}
		}
		if ($this->report)
		{
			echo "<p>Metadata HTTP binding: <b>", $this->httpMetadataBinding, "</b></p>\n";
		}
		$result = ($this->httpMetadataBinding != '');
		return $result;
	}


	function HttpCodeValid($http_code)
	{
		if ( ($http_code == '200') || ($http_code == '302') ){
			return true;
		}
		else{
			return false;
		}
	}

	function GetHTTPMetadata ($l)
	{
		global $config;
	
		$metadata = '';
		$this->lsid_error_code = 0;
		
		// Damian Barnier <dbarnier@gmail.com> noted that having
		// a '/' before ? broke his LSID server, and didn't match the
		// standard.
		// 
		// However, this then broke my Perl servers, as if you don't
		// have the '/' they return HTTP code 301. In a web browser
		// this is fine as the browser follows the location. For curl
		// we need to explicitly set this using CURLOPT_FOLLOWLOCATION.
		//
		// I still get a -2 bytes error with some of my LSID servers. 
		// Need to investigate. Meantime I hack around it.
		//
		$url = $this->httpMetadataBinding . "?lsid=" . $l;
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt ($ch, CURLOPT_HEADER,		  1); // debugging, show header
		curl_setopt ($ch, CURLOPT_PROXY, $this->http_proxy);
		curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
				
		$curl_result = curl_exec ($ch); 
		
		if(( curl_errno ($ch) != 0 ) && ( curl_errno ($ch) != 18 )) // is the missing -2 bytes error
		{
			echo "CURL error: ", curl_error($ch);
		}
		else
		{
		
			 $info = curl_getinfo($ch);
			 $header = substr($curl_result, 0, $info['header_size']);
			 
			 $this->http_code = $info['http_code'];

			 if ($this->HttpCodeValid($this->http_code))
			 {
			 	// Everything seems OK
			 
			 }
			 else
			 {
			 	
			 	// Extract LSID error code, if any
			 	$this->lsid_error_code = 0;
				$rows = split ("\n", $header);
				foreach ($rows as $row)
				{
					$parts = split (":", $row, 2);
					if (count($parts) == 2)
					{
						if (preg_match("/LSID-Error-Code/", $parts[0]))
						{
							$this->lsid_error_code = $parts[1];
						}
					}
				}

			 }
			 
			 if ($this->report)
			 {
				if (!$this->HttpCodeValid($this->http_code))
			 	{
					echo "<p><strong>HTTP error: ", $this->http_code, "</strong></p>";
				}
			 	if ($this->lsid_error_code != 0)
			 	{
					echo "<p><strong>LSID error: ", $this->lsid_error_code, "</strong></p>";
				}
			 	$this->ShowHTTPHeader($header, '7');
			 }
	
			$metadata = substr ($curl_result, $info['header_size']);
			$filename = $this->CacheMetadata($metadata);
			
			if ($this->report)
			{
				$src = "get.php?src=" . $this->lsid->getAuthority() . "/" . $filename ;
				echo "\n<div>\n";
				echo "<table width=\"100%\">\n";
				echo "<tr><td align=\"right\">";
				echo "Display: <select id=\"select\" name=\"select\" onChange=\"switchDisplay(this.options[selectedIndex].value)\">";
				echo "<option value=\"$src&amp;format=xml\" selected>XML</option>\n";
				echo "<option value=\"$src&amp;format=raw\">raw</option>\n";
//				echo "<option value=\"$src&amp;format=rdf\">RDF</option>\n";
				echo "<option value=\"$src&amp;format=png\">Graph PNG</option>\n";
				echo "<option value=\"$src&amp;format=svg\">Graph SVG</option>\n";
				echo "</select>\n";
				echo "</td></tr>\n";
				
				echo '<tr><td align="right"><a href="http://www.w3.org/RDF/Validator/ARPServlet?URI=' 
				. urlencode($config['webroot'] . '/' . $config['cache_prefix'] . '/' . $this->lsid->getAuthority() .  "/" . $filename)
				. '&PARSE=Parse+URI%3A+&TRIPLES_AND_GRAPH=PRINT_BOTH&FORMAT=PNG_EMBED" target="_new">Validate RDF <img border="0" align="absmiddle" src="http://www.w3.org/RDF/icons/rdf_flyer.24"
/></a></td></tr>';
				
				
				echo "<tr><td style=\"border: 1px solid rgb(181,193,223);\"><iframe id=\"metadata\" style=\"width:100%\" frameborder=\"0\" vspace=\"0\" hspace=\"0\" marginwidth=\"0\" marginheight=\"0\" height=\"500\" src=\"$src\"></iframe></td></tr>\n";
				echo "</table>\n";
				echo "</div>\n";
			}
		}
		curl_close ($ch); 
		
		return $metadata;
	}
	
}


// functions

//function GetMetadataForLSID ($l)
//{
//}
	
	
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>LSID Tester</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<style type="text/css">
	body {
		font-family: Lucida Grande,Verdana,Arial,Helvetica, sans-serif;
		font-size: 11px;
		background-color: rgb(247,248,255);
	
	}
	h1 { font-size: 18px; }
	h2 { font-size: 16px; }
	h3 { font-size: 14px; }
	.results {
		border: 1px solid rgb(181,193,223); 
		height:auto; 
		background-color:#ffffff; 
		overflow:auto;
	}
	.search {
		border: 1px solid rgb(181,193,223); 
		height:auto; 
		background-color:#ffffff; 
		overflow:auto;
		align:center;
	}
	.failed {
		border: 1px solid rgb(181,193,223); 
		height:auto; 
		background-color:#ff0000; 
		color: #ffffff;
		text-align: center;
		overflow:auto;
		font-weight:bold;
	}
	.passed {
		border: 1px solid rgb(181,193,223); 
		height:auto; 
		background-color:#00ff00; 
		color: #ffffff;
		text-align: center;
		overflow:auto;
		font-weight:bold;
	}
	.warning {
		border: 1px solid rgb(181,193,223); 
		height:auto; 
		background-color:#ffff00; 
		color: #000000;
		text-align: center;
		overflow:auto;
		font-weight:bold;
	}
	.explanation {
		padding: 2px;
		border: 1px solid rgb(181,193,223); 
		height:auto; 
		background-color:#ffffcc; 
		overflow:auto;
	}
	
	.details td {
		border-top:1px solid rgb(181,193,223);
	}
  	</style>

</head>

<body>


<h1>LSID Tester 0.1</h1>
<p>Written by Rod Page</p>
<p>This is a simple tool for testing a LSID. It is not intended as either an exhaustive
or a definitive test. Source code is available from <a href="http://code.google.com/p/lsid-php/">Google Code</a></p>


<script language="JavaScript" type="text/javascript">

function showElement(id)
{
	var headerRow = document.getElementById(id);
	headerRow.style.display = "block";
	return true;
}
function hideElement(id)
{
	var headerRow = document.getElementById(id);
	headerRow.style.display = "none";
	return true;
}

function showHeaders(prefix)
{
	showElement(prefix + 'headerRow');
	hideElement(prefix + 'showHeaders');
	showElement(prefix + 'collapseHeaders');
	return true;
}

function hideHeaders(prefix)
{
	hideElement(prefix + 'headerRow');
	showElement(prefix + 'showHeaders');
	hideElement(prefix + 'collapseHeaders');
	return true;
}

function switchDisplay(src)
{
	var frame = document.getElementById('metadata');
	frame.src = src;
}
	


</script>

<?php
	
		echo "<div class=\"search\">\n";
echo "<p/>";

echo "<form id=\"textsearch\"  method=\"get\" name=\"textsearch\"  onsubmit=\"return validateTextSearch(this)\">";
echo "<label>LSID: </label>";
echo "<input class=\"search\" name=\"q\" type=\"search\" size=\"60\" autosave=\"taxa\" results=\"10\" placeholder=\"LSID\"";



if (isset($_GET['q'])) { echo "value=\"" . $_GET['q'] . "\"";} 
echo " />";


echo "&nbsp;<input class=\"search\" name=\"submit\" size=\"30\" value=\"Go\" type=\"submit\"  />";
echo "</form>";
echo "<h3>Some example LSIDs</h3>\n";
//echo "<a href=\"?q=", htmlspecialchars("urn:lsid:col2005.gbif.org:col2005:tc-(t.1246388)(d.)(cn.)(r.)") , "\">urn:lsid:col2005.gbif.org:col2005:tc-(t.1246388)(d.)(cn.)(r.)</a><br/>\n";
echo "<a href=\"?q=", htmlspecialchars("urn:lsid:ubio.org:namebank:11815") , "\">urn:lsid:ubio.org:namebank:11815</a><br/>\n";
//echo "<a href=\"?q=", htmlspecialchars("urn:lsid:lsid.zoology.gla.ac.uk:predicates:isBasionymOf") , "\">urn:lsid:lsid.zoology.gla.ac.uk:predicates:isBasionymOf</a><br/>\n";
//echo "<a href=\"?q=", htmlspecialchars("urn:lsid:tdwg.gbif.org:dharma:10298322400") , "\">urn:lsid:tdwg.gbif.org:dharma:10298322400</a><br/>\n";
echo "<a href=\"?q=", htmlspecialchars("urn:lsid:ipni.org:names:20012728-1:1.1") , "\">urn:lsid:ipni.org:names:20012728-1:1.1</a><br/>\n";



echo "<p/>";
echo "</div>\n";



if (isset($_GET['q']))
{
	$l = $_GET['q'];


// test

//$l = 'urn:lsid:indexfungorum.org:Names:213645'; // Index Fungorum - works but serves XML

//	$l = 'urn:lsid:limnology.wisc.edu:category:phys'; // wierd CURL problem
//$l = 'urn:lsid:ubio.org.lsid.zoology.gla.ac.uk:namebankID:345699'; // works
//$l = 'urn:lsid:ncbi.nlm.nih.gov.lsid.biopathways.org:genbank_gi:5851672';
//$l = 'urn:lsid:ubio.org:namebank:345699'; // works

//$l = 'urn:lsid:thep.lu.se:uniprot:Q549G5'; // character case problem (server issue I think)

//$l = 'urn:lsid:tdwg.gbif.org:dharma:10298322400'; // works

//$l = 'urn:lsid:sid.zoology.gla.ac.uk:id:6';

//$l = 'urn:lsid:col2005.gbif.org:col2005:col2005'; // GBFIF


$ok = true;

echo "<h2>Test 1: Valid LSID</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>This test simply asks whether the LSID is correctly formed, that is, it matches the pattern<br/> urn:lsid:&lt;authority&gt;:&lt;namespace&gt;:&lt;object&gt;[:&lt;revision&gt;].</p>\n";
	echo "</div>\n";
	echo "<p/>\n";

$lsid = new LSID($l);
if ($lsid->isValid())
{
	echo "<p/>";
	echo "<div class=\"passed\">\n";
	echo "<p>Passed</p>";
	echo "</div>\n";
}
else
{
	echo "<p/>";
	echo "<div class=\"failed\">\n";
	echo "<p>Failed</p>";
	echo "</div>\n";
	$ok = false;	
}

global $config;
$proxy = '';
if ($config['proxy_name']  != '')
{
	$proxy = $config['proxy_name'] . ":" . $config['proxy_port'];
}
$authority = new Authority($proxy);

if ($ok)
{
	echo "<h2>Test 2: Resolve authority</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>This test looks up the authority of the LSID in the Domain Name Server by looking for a SRV record.</p>\n";
	echo "</div>\n";
	echo "<p/>\n";

	echo "<div class=\"results\">\n";

	$ok = $authority->Resolve($l);

	echo "</div>\n";
}
if ($ok)
{
	echo "<p/>";
	echo "<div class=\"passed\">\n";
	echo "<p>Passed</p>";
	echo "</div>\n";
}
else
{
	echo "<p/>";
	echo "<div class=\"failed\">\n";
	echo "<p>Failed</p>";
	echo "</div>\n";
	$ok = false;	
}


if ($ok)
{
	echo "<h2>Test 3: Authority WSDL</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>We try and retrieve the authority WSDL file by appending &quot;/authority/&quot; to the server address found above. If successful the WSDL is displayed below. You can also see the HTTP headers.</p>";
	echo "</div>\n";
	echo "<p/>\n";

	echo "<div class=\"results\">\n";
	$ok = $authority->GetAuthorityWSDL();
	echo "</div>\n";
	
	if ($ok)
	{
		echo "<p/>";
		echo "<div class=\"passed\">\n";
		echo "<p>Passed</p>";
		echo "</div>\n";
	}
	else	
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed</p>";
		echo "</div>\n";
	}

}

if ($ok)
{
	echo "<h2>Test 4: HTTP binding</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>We now get the HTTP binding for service WSDL from the authority WSDL.</p>\n";
	echo "</div>\n";
	echo "<p/>\n";


	echo "<div class=\"results\">\n";
	$ok = $authority->GetHTTPBinding();
	echo "</div>\n";

	if ($ok)
	{
		if ($authority->bindingIsServerAddress())
		{
			echo "<p/>";
			echo "<div class=\"passed\">\n";
			echo "<p>Passed</p>";
			echo "</div>\n";
		}
		else
		{
			echo "<p/>";
			echo "<div class=\"warning\">\n";
			echo "<p>Warning: HTTP binding is not a server address</p>";
			echo "</div>\n";
		}
	}
	
	else	
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed</p>";
		echo "</div>\n";
	}
}


if ($ok)
{
	echo "<h2>Test 5: Get service WSDL</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>Using the HTTP binding we get the service WSDL which tells us how to get data and/or metadata.</p>\n";
	echo "</div>\n";
	echo "<p/>\n";


	echo "<div class=\"results\">\n";
	$ok = $authority->GetServiceWSDL($l);
	echo "</div>\n";
	
	if ($ok)
	{
		echo "<p/>";
		echo "<div class=\"passed\">\n";
		echo "<p>Passed</p>";
		echo "</div>\n";
		
		$authority->storeServiceWSDL();
		
	}
	else	
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed</p>";
		echo "</div>\n";
	}
}


if ($ok)
{
	echo "<h2>Test 5a: Error handling</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>If we attempt to get a service WSDL with an arbitrary string the LSID authority should return error code 200 &quot;Malformed LSID&quot;</p>\n";
	echo "</div>\n";
	echo "<p/>\n";


	echo "<div class=\"results\">\n";
	$ok = $authority->GetServiceWSDL('xxx');
	echo "</div>\n";
	
	if ($ok == true)
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed: No server or LSID error</p>";
		echo "</div>\n";
	}
	else	
	{
		if ($authority->getLSIDError() == 200)
		{
			echo "<p/>";
			echo "<div class=\"passed\">\n";
			echo "<p>Passed: LSID error 200 returned</p>";
			echo "</div>\n";
		}
		else
		{
			echo "<p/>";
			echo "<div class=\"warning\">\n";
			echo "<p>Warning: Server error but no (or unexpected) LSID error</p>";
			echo "</div>\n";
		}
		
	}
	$ok = true; // keep going
}

if ($ok)
{
	echo "<h2>Test 5b: Error handling</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>If we attempt to get a service WSDL with an arbitrary LSID the authority should return error code 201 &quot;Unknown LSID'&quot;</p>\n";
	echo "</div>\n";
	echo "<p/>\n";


	echo "<div class=\"results\">\n";
	$ok = $authority->GetServiceWSDL('urn:lsid:fred.org:dagg:1');
	echo "</div>\n";
	
	if ($ok == true)
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed: No server or LSID error</p>";
		echo "</div>\n";
	}
	else	
	{
		if ($authority->getLSIDError() == 201)
		{
			echo "<p/>";
			echo "<div class=\"passed\">\n";
			echo "<p>Passed: LSID error 201 returned</p>";
			echo "</div>\n";
		}
		else
		{
			echo "<p/>";
			echo "<div class=\"warning\">\n";
			echo "<p>Warning</p><p>Server error but no (or unexpected) LSID error</p>";
			echo "</div>\n";
		}
		
	}
	$ok = true; // keep going
}

if ($ok)
{
	echo "<h2>Test 6: Get HTTP binding for metadata</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>We now get the HTTP binding for metadata</p>\n";
	echo "</div>\n";
	echo "<p/>\n";


	echo "<div class=\"results\">\n";
	$authority->restoreServiceWSDL();

	$ok = $authority->GetMetadataHTTPLocation();
	echo "</div>\n";
	if ($ok)
	{
		echo "<p/>";
		echo "<div class=\"passed\">\n";
		echo "<p>Passed</p>";
		echo "</div>\n";
	}
	else	
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed</p>";
		echo "</div>\n";
	}
}

if ($ok)
{
	echo "<h2>Test 7: Get metadata</h2>\n";
	echo "<div class=\"explanation\">\n";
	echo "<p>We now get the metadata. ";
	echo "You can display the metadata in various formats, including raw text, formatted XML, and as a graph. ";
	echo "The graph can be downloaded as a dot file, which can be displayed using <a href=\"http://www.graphviz.org/\" target=\"_blank\">Graphviz</a>. ";
	echo "</p>\n";
	echo "</div>\n";
	echo "<p/>\n";


	echo "<div class=\"results\">\n";
	$authority->GetHTTPMetadata($l);
	echo "</div>\n";
	if ($ok)
	{
		echo "<p/>";
		echo "<div class=\"passed\">\n";
		echo "<p>Passed</p>";
		echo "</div>\n";
	}
	else	
	{
		echo "<p/>";
		echo "<div class=\"failed\">\n";
		echo "<p>Failed</p>";
		echo "</div>\n";
	}
}

}


		
// The LTER Apache Tomcat/4.0 server won't play ball with CURL (sigh)
//curl_setopt ($ch, CURLOPT_VERBOSE, 	1); 

//$header[] = "User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1";
//$header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
//$header[] = "Accept-Language: en-us,en;q=0.5";
//$header[] = "Accept-Encoding: gzip,deflate";
//$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
//$header[] = "Keep-Alive: 300";
//$header[] = "Proxy-Connection: keep-alive";

//curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 



?>
